package com.online.teaching.module.teacher.resource.service.impl;

import com.online.teaching.dao.FileMapper;
import com.online.teaching.module.common.file.service.FileService;
import com.online.teaching.module.teacher.resource.service.TeacherResourceService;
import com.online.teaching.pojo.File;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.test.annotation.Rollback;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName : StudentBlogServiceImpl  //类名
 * @Description :   //描述
 * @Author : YG  //作者
 * @Date: 2020-11-04 13:21  //时间
 */
@Service
public class TeacherResourceServiceImpl implements TeacherResourceService {

    @Autowired
    private FileService fileService;

    @Autowired
    private FileMapper fileMapper;

    @Rollback
    @Override
    public int addFile(MultipartFile file, Integer teachesId, Integer parentId, Integer userId) {

        if(file.isEmpty()){
            return 0;
        }
        String fileName=file.getName();
        String address = fileService.upload(file);
        File newFile=new File();
        newFile.setFileAddress(address);
        newFile.setFileName(fileName);
        if(parentId!=null){
            newFile.setParentId(parentId);
        }
        newFile.setType(0);
        newFile.setTeachesId(teachesId);
        fileMapper.insertSelective(new File());

        //更新其父节点状态
        File parent = fileMapper.selectByPrimaryKey(parentId);
        if(parent.getIsParent().equals(0)){
            parent.setIsParent(1);
            return fileMapper.updateByPrimaryKeySelective(parent);
        }
        return 1;

    }

    @Override
    public int addDirectory(String directoryName, Integer teachesId, Integer parentId, Integer userId) {
        File file=new File();
        file.setFileName(directoryName);
        file.setTeachesId(teachesId);
        file.setType(1);
        file.setParentId(parentId);
        fileMapper.insertSelective(file);

        //更新其父节点状态
        File parent = fileMapper.selectByPrimaryKey(parentId);
        if(parent.getIsParent().equals(0)){
            parent.setIsParent(1);
            return fileMapper.updateByPrimaryKeySelective(parent);
        }
        return 1;
    }

    @Rollback
    @Override
    public int deleteResource(Integer id) {
        List<Integer>parentIdList=new ArrayList<>();
        parentIdList.add(id);

        while (parentIdList.size()!=0){
            List<File> files = fileMapper.selectChildren(parentIdList);
            fileMapper.deleteByIdList(parentIdList);
            parentIdList.clear();
            for (int i = 0; i < files.size(); i++) {
                if(!files.get(i).getIsParent().equals(0)){
                    parentIdList.add(files.get(i).getFileId());
                }
            }
        }
        return 1;
    }
}
